/*
 * @Author: yangrongxin
 * @Date: 2021-05-25 14:35:18
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:25:16
 */
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import lottie from 'lottie-miniprogram';
import emptyJson from '@/const/empty';
import { View, Text, Canvas } from '@tarojs/components';
import Taro from '@tarojs/taro';
import styles from './index.module.less';

interface ILotteryEmptyProps {
  emptyNotice?: any; // 提示文字 可以是一个function返回一个字符串
}

/**
 * @description lottery的数据为空动画组件 支持placeholder参数进行提示
 * @returns
 */
const LotteryEmpty = (props: ILotteryEmptyProps, ref) => {
  const { emptyNotice } = props;

  const [renderCanvas, setRenderCanvas] = useState(false);

  useImperativeHandle(ref, () => ({
    initLottie: () => {
      setRenderCanvas(true);
      setTimeout(() => {
        initLottie();
      }, 100);
    },
  }));

  let initEmptyIcon: any; // 存储当前的动画实例对象

  /*
   * 初始化lottie动画
   */
  const initLottie = () => {
    if (initEmptyIcon) {
      initEmptyIcon.play();
      return;
    }
    Taro.createSelectorQuery()
      .select('#empty')
      .node((res: any) => {
        const canvas = res.node;
        const context = canvas.getContext('2d');
        lottie.setup(canvas);
        initEmptyIcon = lottie.loadAnimation({
          rendererSettings: {
            context,
          },
          loop: false,
          autoplay: true,
          animationData: emptyJson,
        });
      })
      .exec();
  };

  return (
    <View className={styles.container}>
      {renderCanvas && <Canvas id="empty" style={{ margin: '0 auto' }} type="2d" />}
      {emptyNotice && renderCanvas && (
        <Text className={styles.emptyNotice}>{typeof emptyNotice === 'function' ? emptyNotice() : emptyNotice}</Text>
      )}
    </View>
  );
};

export default forwardRef(LotteryEmpty);
